from dash import Dash, dash_table, html, callback, Input, Output, State
import dash
import dash_bootstrap_components as dbc
import logging
import logging.handlers
import psycopg2.extras
import pandas as pd
from Units import QUnits

dash.register_page(__name__)

def gruckContainer(parent=None):
    return html.Div(className='panel-group',
                    role='tablist',
                    children=html.Div(className='panel panel-default',
                                      children=html.Div(parent)
                                      )
                    )

def gruckPanel(parent=None):
    return html.Div(
        className='panel-heading',
        role='tab',
        children=html.H4(
            className='panel-title',
            children=html.A(
                children=parent,
                role='button',
                n_clicks=0,
                href="#collapseOne"
            )
        )
    )

def gruckPanelBody(parent=None):
    return html.Div(
        className='panel-collapse',
        role='tabpanel',
        children=dbc.Collapse(
            className='panel-body',
            is_open=False,
            dimension="width",
            children=dbc.Card(
                dbc.CardBody(
                    "This content appeared horizontally due to the "
                    "`dimension` attribute"
                    + parent
                ),
                style={"width": "400px"}
            )
        )
    )

def layout():
    panel = list()
    unit = QUnits()
    setting = unit.XML2ObjFromFile('./setting.xml').setting
    try:
        conn = unit.dbConnect(setting.pgsql)
        cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
        cursor.execute('SELECT * FROM trading.position WHERE stock_code IS NOT NULL')
        for row in cursor.fetchall():
            panelTitle = row['stock_code'] + '（' + row['stock_code'] + '），持仓成本：￥' + str(row['capitalized']) + '，持仓数量：' + str(row['number']) + '股'
            panel.append(gruckPanel(panelTitle))
            panel.append(gruckPanelBody('sdgsdgsdgsdgsdgsdgsdgsdg'))
    except Exception as e:
        logging.warning(str(e))
    finally:
        unit.dbDisconnect(conn)
    return gruckContainer(panel)

@callback(
    Output("horizontal-collapse", "is_open"),
    [Input("horizontal-collapse-button", "n_clicks")],
    [State("horizontal-collapse", "is_open")],
)
def toggle_collapse(n, is_open):
    if n:
        return not is_open
    return is_open